<template>
  <a-modal title-align="start" :title="props.type == 'add' ? '添加属性' : '编辑属性'" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="900">
    <div v-if="props.type == 'add'">
      <a-space>
        <a-select style="width: 180px" placeholder="请选择属性" @change="changeAtt" allow-search v-model="selAttrId">
          <a-option v-for="(item, index) of attrDataList" :key="index" :value="item.id">{{ item.name }}</a-option>
        </a-select>
        <a-button class="gray-outline">新增</a-button>
      </a-space>
      <a-table size="mini" :data="editSelAttr" :pagination="false" :loading="attrLoading" class="table-single-line mt5" :scroll="{ x: '100%', y: 300 }">
        <template #columns>
          <a-table-column title="属性ID" #cell="{ record }" :width="80">
            {{ record.id }}
          </a-table-column>
          <a-table-column title="属性名称" #cell="{ record }" :width="100">
            {{ record.name }}
          </a-table-column>
          <a-table-column title="可见性" #cell="{ record }" :width="100">
            <a-checkbox v-model="record.visible" disabled>产品页可见</a-checkbox>
            <a-checkbox v-model="record.variation">变体可用</a-checkbox>
          </a-table-column>
          <a-table-column title="属性值" #cell="{ record }" :width="300">
            <a-button type="text" @click="showEditAttrValueModal(record)">新增或者修改属性值</a-button>
            <a-button class="fr" type="text" @click="show(record)">添加属性值</a-button>
            <TextLimit position="top" :val="record.selKey.join('，')"></TextLimit>

            <!-- <div>
              <a-checkbox-group v-model="record.selKey">
                <a-checkbox v-for="(item, index) of record.options" :key="index" :value="item">{{ item }}</a-checkbox>
              </a-checkbox-group>
            </div>
            <div class="clearfix mt10" style="height: 32px; line-height: 32px">
              <a-checkbox class="fl" v-model="record.selAll" @change="selAll($event, record)">
                <span class="common-text">全选</span>
              </a-checkbox>
              <a-button class="fr" type="text" @click="show(record)">添加属性值</a-button>
            </div> -->
          </a-table-column>
        </template>
      </a-table>
    </div>
    <div v-else>
      <div class="mt5 edit-detail-item">
        <a-space>
          <div class="title">属性ID:</div>
          <div>{{ editInfo.id }}</div>
        </a-space>
      </div>
      <div class="mt5 edit-detail-item">
        <a-space>
          <div class="title">属性名称:</div>
          <div>{{ editInfo.name }}</div>
        </a-space>
      </div>
      <div class="mt5 edit-detail-item">
        <a-space>
          <div class="title">可见性:</div>
          <div>
            <a-checkbox disabled v-model="editInfo.visible">产品页可见</a-checkbox>
            <a-checkbox v-model="editInfo.variation">变体可用</a-checkbox>
          </div>
        </a-space>
      </div>
      <div class="mt5 edit-detail-item">
        <a-space>
          <div class="title">属性:</div>
          <div>
            <a-button class="fr" type="text" @click="show(editInfo)">添加属性值</a-button>
          </div>
        </a-space>
      </div>
      <div class="mt5 edit-detail-item">
        <a-space>
          <a-input v-model.trim="editSearchstr" allow-clear style="width: 200px" placeholder="请输入属性值" />
          <a-button class="gray-outline" @click="searchAttList">搜索</a-button>
        </a-space>

        <a-table :pagination="false" class="table-single-line mt5" v-model:selected-keys="editInfo.selKey" row-key="name" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false, width: 20 }" :loading="attrLoading" :data="attrOptions" :scroll="{ x: '100%', y: 300 }">
          <template #columns>
            <a-table-column title="属性值" #cell="{ record }" :width="500">
              {{ record.name }}
            </a-table-column>
          </template>
        </a-table>

        <div class="pagination-footer mt10">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="editInfo.options.length" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>

        <!-- <a-space>
          <div class="title">
            <a-checkbox v-model="editIsSelAll" @change="editSelAll">全选</a-checkbox>
          </div>
          <div>
            <a-checkbox-group v-model="editInfo.selKey">
              <a-checkbox v-for="(item, index) of editInfo.options" :key="index" :value="item">{{ item }}</a-checkbox>
            </a-checkbox-group>
          </div>
        </a-space> -->
      </div>
    </div>
    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" @click="submit">确定</a-button>
    </template>

    <quickAddAtt v-if="quickAddAttModal" v-model="quickAddAttModal" :id="id" :shopId="props.shopId" @save="save" />

    <editAttrValue v-if="editAttrValueModal" v-model="editAttrValueModal" :info="addInfo" @save="save" />
  </a-modal>
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed } from 'vue'
  import { attributeRollPage } from '@/api/product'
  import quickAddAtt from './quickAddAtt.vue'
  import editAttrValue from './editAttrValue.vue'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'type', 'info', 'selAttList', 'shopId'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let id = ref('')
  let quickAddAttModal = ref(false)
  let editIsSelAll = ref(false)
  let attrLoading = ref(false)
  let editAttrValueModal = ref(false)
  let attrDataList: any = ref([])
  let selAttrId = ref('')
  let editSearchstr = ref('')
  let pageNation = ref({ pageNum: 1, pageSize: 50 })
  let attrOptions: any = ref([])
  let addInfo = ref({})
  let editInfo: any = ref({
    options: [],
  })
  // 编辑的时候存一份原始数据
  let initAttDataList: any = ref([])
  let editSelAttr: any = ref([])
  const getList = async () => {
    try {
      attrLoading.value = true
      const res: any = await attributeRollPage({ shopIdList: [props.shopId], pageSize: 999999 })
      let arr = res.data?.list || []
      // 接口返回的数据处理成传参格式
      // console.log(arr, props.selAttList)
      arr.forEach((e: any) => {
        let obj = {
          id: e.dataFromRestApi.id || '',
          name: e.dataFromRestApi.name || '',
          options: e.termList ? e.termList.map((e: any) => e.dataFromRestApi.name) : [],
          position: 0,
          variation: true,
          visible: true,
        }
        attrDataList.value.push(obj)
      })
      // 处理数据
      props.type == 'add' ? setNewAttr() : setEditNewAttr()
    } catch (error) {}
    attrLoading.value = false
  }
  const setNewAttr = () => {
    // 对比一下，选中的数据
    props.selAttList.forEach((e: any) => {
      let index = attrDataList.value.findIndex((item: any) => item.id == e.id)
      if (index != -1) {
        let obj = _.cloneDeep(e)
        obj.selKey = [...obj.options]
        obj.options = [...attrDataList.value[index].options]
        if (obj.selKey.length == obj.options.length) obj.selAll = true
        editSelAttr.value.push(obj)

        console.log(editSelAttr.value)
      }
    })
  }

  const setEditNewAttr = () => {
    let obj = _.cloneDeep(props.info)
    let index = attrDataList.value.findIndex((item: any) => item.id == obj.id)
    if (index != -1) {
      obj.selKey = [...obj.options]
      obj.options = [...attrDataList.value[index].options]
      initAttDataList.value = [...attrDataList.value[index].options]
      editInfo.value = obj
      console.log(obj)

      // 由于属性值太多，所以这个地方前端做一下分页
      changeSizeToEditAttData()
    }
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    changeSizeToEditAttData()
  }

  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    changeSizeToEditAttData()
  }

  const changeSizeToEditAttData = () => {
    attrOptions.value = []
    let arr = editInfo.value.options.slice(pageNation.value.pageSize * (pageNation.value.pageNum - 1), pageNation.value.pageSize * pageNation.value.pageNum)
    arr.forEach((e: any) => {
      let obj = { name: e }
      attrOptions.value.push(obj)
    })
  }

  const searchAttList = () => {
    if (editSearchstr.value) {
      editInfo.value.options = initAttDataList.value.filter((e: any) => e.includes(editSearchstr.value))
    } else {
      editInfo.value.options = initAttDataList.value
    }
    pageNation.value.pageNum = 1
    changeSizeToEditAttData()
  }

  const showEditAttrValueModal = (data: any) => {
    addInfo.value = data
    editAttrValueModal.value = true
  }

  const selAll = (type: boolean, data: any) => {
    type ? (data.selKey = [...data.options]) : (data.selKey = [])
  }

  const show = (data: any) => {
    id.value = data.id
    quickAddAttModal.value = true
  }

  const save = (name: string) => {
    if (props.type == 'add') {
      let item = editSelAttr.value.find((e: any) => e.id == id.value)
      item.options.push(name)
      item.selKey.push(name)
    } else {
      editInfo.value.options.push(name)
      editInfo.value.selKey.push(name)
    }
  }

  const changeAtt = (val: string) => {
    let item = attrDataList.value.find((e: any) => e.id == val)
    let index = editSelAttr.value.findIndex((e: any) => e.id == item.id)
    selAttrId.value = ''
    if (index != -1) return
    if (item) {
      item.selKey = [...item.options].slice(0, 100)
      item.selAll = true
      editSelAttr.value.push(item)
    }
  }

  const editSelAll = (val: boolean) => {
    val ? (editInfo.value.selKey = [...editInfo.value.options]) : (editInfo.value.selKey = [])
  }

  const submit = () => {
    let arr = _.cloneDeep(editSelAttr.value)
    if (props.type == 'add') {
      arr.map((e: any) => {
        e.options = e.selKey && [...e.selKey]
        return e
      })
      emits('save', arr)
    } else {
      let obj = _.cloneDeep(editInfo.value)
      obj.options = obj.selKey && [...obj.selKey]
      emits('save', obj)
    }
    showvisible.value = false
  }

  onMounted(() => {
    getList()
  })
</script>

<style lang="less" scoped>
  .title {
    width: 70px;
    text-align: right;
  }
</style>
